package com.biodiv.client.handler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @Author: tianquan
 * @CreateTime: 2025-05-23  18:09
 * @Description: 断开服务器连接处理器
 */
@Slf4j
@ChannelHandler.Sharable
public class RetryConnectServerHandler implements ChannelFutureListener {

    private final Bootstrap bootstrap;
    private final InetSocketAddress address;

    public RetryConnectServerHandler(Bootstrap bootstrap, InetSocketAddress address) {
        this.bootstrap = bootstrap;
        this.address = address;
    }

    @Override
    public void operationComplete(ChannelFuture future) {
        if (!future.isSuccess()) {
            handleRetry();
            return;
        }
        Channel channel = future.channel();
        // 如果连接成功，监听连接关闭事件
        channel.closeFuture().addListener((ChannelFutureListener) cf -> {
            log.warn("Connection to server closed unexpectedly.");
            handleRetry();
        });
    }

    private void handleRetry() {
        log.warn("Connection failed or closed. Retry");
        scheduleRetry();
    }

    public void scheduleRetry() {
        EventLoop eventLoop = bootstrap.config().group().next();
        eventLoop.schedule(() -> {
            log.info("Attempting reconnection...");
            bootstrap.connect(address).addListener(this);
        }, 2, TimeUnit.SECONDS);
    }

}
